package cn.schoolwow.quickserver.handler;

import cn.schoolwow.quickserver.domain.Client;
import cn.schoolwow.quickserver.domain.HttpSessionMeta;
import com.sun.java.accessibility.util.AccessibilityListenerList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpCookie;
import java.util.Date;
import java.util.UUID;

/**
 * Http会话处理
 */
public class HttpSessionHandler implements Handler {
    public static final String SESSION = "quickServerSession";
    private Logger logger = LoggerFactory.getLogger(HttpSessionHandler.class);

    @Override
    public Handler handle(Client client) throws IOException {
        HttpCookie sessionCookie = client.httpRequestMeta.cookieList.stream().filter(httpCookie -> httpCookie.getName().equalsIgnoreCase(SESSION)).findFirst().orElse(null);
        if(null!=sessionCookie){
            logger.trace("[获取会话id]{}={}",sessionCookie.getName(),sessionCookie.getValue());
        }
        if (null == sessionCookie || !client.serverConfigMeta.sessionMap.containsKey(sessionCookie.getValue())) {
            //创建会话
            client.httpSessionMeta.id = UUID.randomUUID().toString();
            client.httpSessionMeta.createdTime = System.currentTimeMillis();
            client.serverConfigMeta.sessionMap.put(client.httpSessionMeta.id, client.httpSessionMeta);
            sessionCookie = new HttpCookie(SESSION, client.httpSessionMeta.id);
            sessionCookie.setPath("/");
            sessionCookie.setHttpOnly(true);
            sessionCookie.setSecure(false);
            sessionCookie.setMaxAge(client.serverConfigMeta.sessionTimeout);
            sessionCookie.setVersion(0);
            client.httpResponse.addCookie(sessionCookie);
            logger.trace("[创建会话]会话id:{}", client.httpSessionMeta.id);
        }else{
            client.httpSessionMeta = client.serverConfigMeta.sessionMap.get(sessionCookie.getValue());
            client.httpSessionMeta.lastAccessedTime = System.currentTimeMillis();
            logger.trace("[会话已存在]上次访问:{},会话属性:{}", new Date(client.httpSessionMeta.lastAccessedTime),client.httpSessionMeta.attributes);
        }
        return new DispatcherHandler();
    }
}
